package com.ews.onlineexchange.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.TradeStatus;
import com.ews.onlineexchange.model.User;

@Model
@RolesAllowed( value = "buyer" )
public class BuyerPassedBulletinList extends EntityQuery<Bulletin> {

	private static final long	serialVersionUID	= 1L;

	@Inject
	UserService					userService;

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<Bulletin> entity ) {
		// TODO Auto-generated method stub
		User loginedUser = userService.getLoginedUser();
		List<Predicate> restrictions = new ArrayList<>();
		Join<Trade, ServiceBuyer> buyer = entity.join( "buyer" );
		restrictions.add( cb.equal( buyer.get( "username" ), loginedUser.getUsername() ) );
		restrictions.add( cb.isTrue( entity.<Boolean>get( "over" ) ) );
		// 过滤已经取消的公告
		restrictions.add( cb.isFalse( entity.<Boolean>get( "cancelled" ) ) );
		restrictions.add( cb.equal( entity.get( "tradeStatus" ), TradeStatus.Passed ) );
		String projectName = (String) getParameterValues().get( "projectName" );
		if ( !StringUtils.isBlank( projectName ) )
			restrictions.add( cb.like( entity.get( "projectName" ), getStringRestriction( projectName ) ) );

		String serialNumber = (String) getParameterValues().get( "serialNumber" );
		if ( !StringUtils.isBlank( serialNumber ) )
			restrictions.add( cb.like( entity.get( "serialNumber" ), getStringRestriction( serialNumber ) ) );
		return restrictions;
	}

	public BuyerPassedBulletinList() {
		super();
		setOrder( "createDate desc" );
	}

}
